
<template>
  <div class="chat-page">
    <header class="chat-header">
      <el-button link @click="goBack">← 返回</el-button>
      <div class="chat-title">
        <el-avatar :size="36" :src="character?.image" :icon="User" />
        <div class="title-text">
          <div class="name">{{ character?.name || '对话' }}</div>
        </div>
      </div>
      <div class="header-actions">
        <el-button size="small" @click="showSessionList = true">历史对话</el-button>
        <el-button size="small" type="primary" @click="createNewSession">新建对话</el-button>
      </div>
    </header>

    <main class="chat-main" ref="scrollContainer">
      <div v-if="messages.length === 0" class="empty-tip">
        {{ getCurrentSessionTip() }}
      </div>
      <div v-for="(m, idx) in messages" :key="idx" class="msg-item" :class="m.role">
        <el-avatar v-if="m.role === 'assistant'" :size="28" :src="character?.image" :icon="User" />
        <div class="bubble" v-text="m.content"></div>
        <el-avatar v-if="m.role === 'user'" :size="28" :src="userAvatar" icon="User" />
      </div>
    </main>

    <footer class="chat-input">
      <el-input
        v-model="input"
        type="textarea"
        :rows="2"
        placeholder="输入消息，Enter 发送，Shift+Enter 换行"
        @keydown.enter.prevent="handleEnter"
      />
      <div class="input-actions">
        <el-button type="primary" :loading="sending" @click="send">
          发送
        </el-button>
      </div>
    </footer>

    <!-- 会话列表弹窗 -->
    <el-drawer v-model="showSessionList" title="历史对话" size="400px">
      <div class="session-list">
        <div class="session-list-header">
          <el-button type="primary" size="small" @click="createNewSession">新建对话</el-button>
          <el-button size="small" @click="loadSessionList">刷新</el-button>
        </div>
        
        <div v-if="sessionList.length === 0" class="empty-sessions">
          暂无历史对话
        </div>
        
        <div v-for="session in sessionList" :key="session.sessionId" 
             class="session-item" 
             :class="{ active: session.sessionId === currentSessionId }"
             @click="switchToSession(session)">
          <div class="session-header">
            <div class="session-title">{{ session.title || '对话' }}</div>
            <div class="session-time">{{ formatTime(session.updateTime) }}</div>
          </div>
          <div class="session-preview">{{ session.lastMessage || '暂无消息' }}</div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'
// removed: import api from '../api/config'
import { characterApi } from '../api/character'
import { chatApi } from '../api/chat'
import { userApi } from '../api/user'

interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
}

interface SessionInfo {
  sessionId: string
  createTime: string
  updateTime: string
  title: string
  lastMessage: string
}

const route = useRoute()
const router = useRouter()
const characterId = route.params.id as string

// 获取用户ID
const userId = ref<string>(getUserId())

const character = ref<any>(null)
const messages = ref<ChatMessage[]>([])
const input = ref('')
const sending = ref(false)
const scrollContainer = ref<HTMLElement | null>(null)
const userAvatar = ref('')

// 会话管理相关
const currentSessionId = ref<string>('')
const defaultSessionId = ref<string>('')
const showSessionList = ref(false)
const sessionList = ref<SessionInfo[]>([])

const goBack = () => router.back()

/**
 * 获取用户ID
 */
function getUserId(): string {
  const storedUserId = localStorage.getItem('userId')
  if (storedUserId) return storedUserId
  
  const tempUserId = `temp_user_${Date.now()}`
  localStorage.setItem('userId', tempUserId)
  return tempUserId
}

/**
 * 获取当前会话的提示信息
 */
const getCurrentSessionTip = () => {
  if (currentSessionId.value === defaultSessionId.value) {
    return '开始发送消息，和TA聊聊吧～'
  }
  const session = sessionList.value.find(s => s.sessionId === currentSessionId.value)
  return session ? `当前对话：${session.title}，继续聊天吧～` : '这是一个新的对话，开始聊天吧～'
}

/**
 * 格式化时间显示
 */
const formatTime = (timestamp: string) => {
  const time = new Date(Number(timestamp))
  const now = new Date()
  const diff = now.getTime() - time.getTime()
  
  if (diff < 60 * 1000) return '刚刚'
  if (diff < 60 * 60 * 1000) return `${Math.floor(diff / (60 * 1000))}分钟前`
  if (diff < 24 * 60 * 60 * 1000) return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
  
  const month = time.getMonth() + 1
  const day = time.getDate()
  const hour = time.getHours()
  const minute = time.getMinutes()
  return `${month}月${day}日 ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
}

const scrollToBottom = async () => {
  await nextTick()
  const el = scrollContainer.value
  if (el) el.scrollTop = el.scrollHeight
}

const loadCharacter = async () => {
  try {
    const res = await characterApi.getDetail(Number(characterId))
    character.value = res.data
  } catch (e) {
    console.error('加载角色失败:', e)
  }
}

// 加载用户头像
const loadUserAvatar = async () => {
  try {
    const resp = await userApi.getAvatar()
    if ((resp.code === 1 || resp.code === 0) && resp.data) {
      userAvatar.value = resp.data
    }
  } catch (e) {
    console.error('加载用户头像失败:', e)
  }
}

/**
 * 获取上次使用的会话ID
 */
const getLastUsedSessionId = (): string | null => {
  const key = `lastSession_${userId.value}_${characterId}`
  return localStorage.getItem(key)
}

/**
 * 保存当前使用的会话ID
 */
const saveLastUsedSessionId = (sessionId: string) => {
  const key = `lastSession_${userId.value}_${characterId}`
  localStorage.setItem(key, sessionId)
}

/**
 * 智能选择要加载的会话
 */
const selectSessionToLoad = async (): Promise<string> => {
  // 1. 先加载会话列表
  await loadSessionList()
  
  // 2. 获取上次使用的会话ID
  const lastUsedSessionId = getLastUsedSessionId()
  
  // 3. 如果有上次使用的会话，且在会话列表中存在，则使用它
  if (lastUsedSessionId && sessionList.value.some(session => session.sessionId === lastUsedSessionId)) {
    console.log('加载上次使用的会话:', lastUsedSessionId)
    return lastUsedSessionId
  }
  
  // 4. 如果没有上次使用的会话，或者上次使用的会话已不存在，选择最新的会话
  if (sessionList.value.length > 0) {
    // 会话列表已按updateTime倒序排列，第一个就是最新的
    const latestSession = sessionList.value[0]
    console.log('加载最新的会话:', latestSession.sessionId)
    return latestSession.sessionId
  }
  
  // 5. 如果没有任何会话，使用默认会话
  console.log('使用默认会话:', defaultSessionId.value)
  return defaultSessionId.value
}

/**
 * 加载会话列表
 */
const loadSessionList = async () => {
  try {
    const resp = await chatApi.getSessionList(userId.value, characterId)
    if (resp.data && Array.isArray(resp.data)) {
      sessionList.value = resp.data
    }
  } catch (e) {
    console.error('加载会话列表失败:', e)
    ElMessage.error('加载会话列表失败')
  }
}

/**
 * 加载指定会话的聊天历史记录
 */
const loadHistory = async (sessionId: string) => {
  try {
    let resp
    if (sessionId === defaultSessionId.value) {
      resp = await chatApi.getDefaultHistory(userId.value, characterId)
    } else {
      resp = await chatApi.getSessionHistory(sessionId)
    }
    if (resp.data && Array.isArray(resp.data)) {
      messages.value = resp.data.map((msg: any) => ({
        role: msg.type === 'user' ? 'user' : 'assistant',
        content: msg.content
      }))
      await scrollToBottom()
    }
  } catch (e) {
    console.error('加载历史记录失败:', e)
  }
}

/**
 * 创建新会话
 */
const createNewSession = async () => {
  try {
    // 直接创建新会话，不弹出标题输入框
    const resp = await chatApi.newSession(characterId, '新对话')
    if (resp.data) {
      const newSessionId = resp.data
      currentSessionId.value = newSessionId
      messages.value = []
      saveLastUsedSessionId(newSessionId)
      await loadSessionList()
      showSessionList.value = false
      ElMessage.success('新对话已创建')
    }
  } catch (e) {
    console.error('创建新会话失败:', e)
    ElMessage.error('创建新会话失败')
  }
}

/**
 * 切换到指定会话
 */
const switchToSession = async (session: SessionInfo) => {
  if (session.sessionId === currentSessionId.value) {
    showSessionList.value = false
    return
  }
  
  currentSessionId.value = session.sessionId
  
  // 保存为最新使用的会话
  saveLastUsedSessionId(session.sessionId)
  
  await loadHistory(session.sessionId)
  showSessionList.value = false
  ElMessage.success(`已切换到：${session.title}`)
}

const send = async () => {
  if (!input.value.trim()) return
  const content = input.value
  messages.value.push({ role: 'user', content })
  input.value = ''
  await scrollToBottom()
  try {
    sending.value = true
    const roleParams: Record<string, string> = {}
    if (character.value) {
      roleParams.name = character.value.name || ''
      roleParams.appearance = character.value.appearance || ''
      roleParams.background = character.value.background || ''
      roleParams.personality = character.value.personality || ''
      roleParams.classicLines = character.value.classicLines || ''
    }
    const params = {
      memoryId: currentSessionId.value,
      userId: userId.value,
      characterId,
      message: content,
      ...roleParams
    }
    const resp = await chatApi.sendMessage(params)
    const replyText = typeof resp === 'string' ? resp : (resp?.data || '')
    messages.value.push({ role: 'assistant', content: String(replyText) })
    saveLastUsedSessionId(currentSessionId.value)
    await loadSessionList()
  } catch (e: any) {
    console.error('发送消息失败:', e)
    ElMessage.error('发送失败，请重试')
  } finally {
    sending.value = false
    await scrollToBottom()
  }
}

const handleEnter = (ev: KeyboardEvent) => {
  if (ev.shiftKey) return
  ev.preventDefault()
  if (!sending.value) send()
}

onMounted(async () => {
  // 初始化默认会话ID
  defaultSessionId.value = `chat_${userId.value}_${characterId}`
  
  await loadCharacter()
  await loadUserAvatar()
  
  // 智能选择要加载的会话
  const sessionToLoad = await selectSessionToLoad()
  currentSessionId.value = sessionToLoad
  
  // 加载选定会话的历史记录
  await loadHistory(sessionToLoad)
  await scrollToBottom()
})
</script>

<style scoped>
.chat-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.chat-title .name {
  font-weight: 600;
  color: #ec4899;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.chat-main {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #fff5fb;
  min-height: 0;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 20px;
}

.msg-item {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  margin-bottom: 12px;
}

.msg-item.user { 
  justify-content: flex-end; 
}

.bubble {
  max-width: 70%;
  padding: 10px 12px;
  border-radius: 10px;
  background: #fff;
  box-shadow: 0 2px 6px rgba(0,0,0,0.06);
  white-space: pre-wrap;
  word-break: break-word;
}

.msg-item.user .bubble {
  background: #ec4899;
  color: #fff;
}

.chat-input {
  padding: 10px 16px;
  border-top: 1px solid #f0f0f0;
  background: #fff;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

/* 会话列表样式 */
.session-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.session-list-header {
  display: flex;
  gap: 8px;
  padding: 0 0 16px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 16px;
}

.empty-sessions {
  text-align: center;
  color: #999;
  padding: 40px 20px;
}

.session-item {
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  border: 1px solid transparent;
  margin-bottom: 8px;
  transition: all 0.2s ease;
}

.session-item:hover {
  background: #f5f5f5;
  border-color: #e0e0e0;
}

.session-item.active {
  background: #fff5fb;
  border-color: #ec4899;
}

.session-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.session-title {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.session-time {
  font-size: 12px;
  color: #999;
}

.session-preview {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
